<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="话题名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入话题名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['knowledge:topic:add']" :disabled="addButtonDisabled">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['knowledge:topic:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['knowledge:topic:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['knowledge:topic:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="topicList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="话题ID" align="center" prop="id" />
      <el-table-column label="话题名称" align="center" prop="name" />
      <!-- 话题图片列：支持预览 + 占位 -->
      <el-table-column label="话题图片" align="center">
        <template slot-scope="scope">
          <el-image v-if="scope.row.url" :src="scope.row.url" style="width: 100px; height: 100px; object-fit: contain"
            :preview-src-list="[scope.row.url]" lazy></el-image>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['knowledge:topic:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['knowledge:topic:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改话题管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="话题名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入话题名称" />
        </el-form-item>
        <!-- 话题图片上传组件 -->
        <el-form-item label="话题图片" prop="url">
          <el-upload class="avatar-uploader" :action="uploadUrl" :headers="uploadHeaders" :show-file-list="true"
            :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload"
            :file-list="fileList" list-type="picture">
            <img v-if="form.url" :src="form.url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div style="margin-top: 10px; font-size: 12px; color: #606266;">
            提示：支持JPG、PNG格式，大小不超过2MB
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listTopic,
    getTopic,
    delTopic,
    addTopic,
    updateTopic
  } from "@/api/knowledge/topic"
  import {
    getToken
  } from "@/utils/auth" // 导入token工具

  export default {
    name: "Topic",
    dicts: ['sys_normal_disable'],
    data() {
      return {
        loading: true,
        ids: [],
        single: true,
        multiple: true,
        showSearch: true,
        total: 0,
        topicList: [],
        title: "",
        open: false,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          del: null
        },
        // 表单数据（新增url字段）
        form: {
          id: null,
          name: null,
          url: null, // 图片URL
          del: null
        },
        // 上传配置
        uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 复用系统上传接口
        uploadHeaders: {
          Authorization: "Bearer " + getToken() // 携带认证token
        },
        fileList: [], // 上传文件列表
        // 表单校验（新增url校验）
        rules: {
          name: [{
            required: true,
            message: "话题名称不能为空",
            trigger: "blur"
          }],
          url: [{
            required: true,
            message: "请上传话题图片",
            trigger: "change"
          }]
        },
        addButtonDisabled: true
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.loading = true
        listTopic(this.queryParams).then(response => {
          this.topicList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      cancel() {
        this.open = false
        this.reset()
      },
      // 重置表单（新增fileList清空）
      reset() {
        this.form = {
          id: null,
          name: null,
          url: null,
          del: null
        }
        this.fileList = [] // 清空上传文件列表
        this.resetForm("form")
      },
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      resetQuery() {
        this.resetForm("queryForm")
        this.handleQuery()
      },
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      handleAdd() {
        this.reset()
        this.open = true
        this.title = "添加话题管理"
      },
      // 编辑时回显图片
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        getTopic(id).then(response => {
          this.form = response.data;
          // 回显已上传的图片（确保form.url和fileList同步）
          if (this.form.url) {
            this.fileList = [{
              name: 'topic-image',
              url: this.form.url, // 直接使用form.url
              uid: Date.now() // 添加唯一标识，避免el-upload内部报错
            }];
          }
          this.open = true;
          this.title = "修改话题管理";
        });
      },
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateTopic(this.form).then(() => {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              })
            } else {
              addTopic(this.form).then(() => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$modal.confirm('是否确认删除话题管理编号为"' + ids + '"的数据项？').then(() => {
          return delTopic(ids)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(() => {})
      },
      handleExport() {
        this.download('knowledge/topic/export', {
          ...this.queryParams
        }, `topic_${new Date().getTime()}.xlsx`)
      },
      // 上传成功回调
      handleUploadSuccess(response, file, fileList) {
        console.log("上传响应：", response);
        if (response.code === 200) {
          // 1. 赋值 URL
          this.form.url = response.url;
          this.fileList = fileList;

          // 2. 强制触发 Vue 响应式更新（解决异步赋值延迟问题）
          this.$forceUpdate();

          // 3. 下一个 DOM 周期后，强制校验 url 字段
          this.$nextTick(() => {
            this.$refs.form.validateField('url');
          });

          this.$modal.msgSuccess("上传成功");
        } else {
          this.$modal.msgError(response.msg || "上传失败");
        }
      },
      // 上传失败回调
      handleUploadError() {
        this.$modal.msgError("上传失败，请重试")
      },
      // 上传前校验（格式+大小）
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJPG) {
          this.$modal.msgError('只能上传JPG/PNG格式的图片')
          return false
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$modal.msgError('图片大小不能超过2MB')
          return false
        }
        return true
      }
    }
  }
</script>

<style scoped>
  /* 图片上传样式（复用文章组件的样式） */
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }

  .avatar {
    width: 150px;
    height: 150px;
    display: block;
    object-fit: contain;
  }
</style>
